﻿using LmgCMS.Model;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Swashbuckle.AspNetCore.Swagger;
using System.Data;
using System.Text;
using UEditor.Core;

namespace LmgCMS.Areas.API.Controllers
{
    /// <summary>
    /// 通用表选择器配合selectTable使用
    /// </summary>
    [ApiExplorerSettings(GroupName = SwaggerGroupingModel.GROUPNAME_COMM)]
    public class TableSelectorController : BaseController
    {
        private IDbSession _dbSession = null;
        public TableSelectorController()
        {
            _dbSession = DbFactory.DbHelper();
        }
        [HttpPost]
        public IActionResult search()
        {
            PageGridViewModel pageGrid = new PageGridViewModel();
            var pageNumber = Utils.GetObjTranNull<int>(Request.Form["pageNumber"].ToString());
            var offset = string.IsNullOrWhiteSpace(Request.Form["offset"].ToString()) ? "1" : Request.Form["offset"].ToString();
            var limit = string.IsNullOrWhiteSpace(Request.Form["limit"].ToString()) ? 10 : Utils.GetObjTranNull<int>(Request.Form["limit"].ToString());
            var tableName = Request.Form["tableName"].ToString();
            var conditions = Request.Form["conditions"].ToString();
            var sort = string.IsNullOrWhiteSpace(Request.Form["sort"].ToString()) ? "id" : Request.Form["sort"].ToString();
            var order = string.IsNullOrWhiteSpace(Request.Form["order"].ToString()) ? "desc" : Request.Form["order"].ToString();
            var sql = Request.Form["sql"].ToString();

            var search = Request.Form["search"].ToString();
            var searchField = string.IsNullOrWhiteSpace(Request.Form["searchField"].ToString()) ? "*" : Request.Form["searchField"].ToString();

            StringBuilder _whereStr = new StringBuilder();
            if (!string.IsNullOrWhiteSpace(conditions) && conditions.Contains("whereStr"))
            {
                JObject _jObject = JObject.Parse(conditions);
                _whereStr.Append(_jObject["whereStr"].ToString());
            }
            else
            {
                JObject _jObject = JObject.Parse(conditions);
                List<string> listSql = new List<string>();
                foreach (JProperty item in _jObject.Children())
                {
                    listSql.Add($" {item.Name}='{item.Value}' ");
                }
                _whereStr.Append(string.Join(" and ", listSql.ToArray()));
            }
            if (!string.IsNullOrWhiteSpace(search) && !string.IsNullOrWhiteSpace(searchField))
            {
                if (_whereStr.Length > 5) { _whereStr.Append($" and "); }
                _whereStr.Append($" {searchField} LIKE '%{search}%' ");
            }

            if (!string.IsNullOrWhiteSpace(sql))
            {
                //DOTO: SQL查询条件和排序
                string orderby = sort + " " + order;
                string sqlStr = sql.DecodeBase64();
                var data = _dbSession.ExecuteDataTable(sqlStr);
                pageGrid.rows = data;
                pageGrid.total = data.Rows.Count.ToString();
                pageGrid.other = "";
            }
            else
            {
                string orderby = sort + " " + order;
                pageGrid.rows = _dbSession.GetListByPage(_whereStr.ToString(), orderby, pageNumber, limit, tableName);
                pageGrid.total = _dbSession.GetRecordCount(_whereStr.ToString(), tableName).ToString();
                pageGrid.other = "";
            }
            return Content(pageGrid.ToJson());

        }
    }
    public class PageGridViewModel
    {
        public object rows { get; set; }
        public string total { get; set; }
        public string other { get; set; }
    }
}
